/* 导入班级名单 */
let dons =false
window.callbacks = {
    list: function() {
        let list = arguments[0]
        let none = document.querySelector('.none')
        let con = document.querySelector('.homeWork .con')
        if (!list) return none.style.display = 'block'
        if (!Array.isArray(list)) return console.warn('List need Array type')
        none.style.display = 'none'
        toDom(con, list)
    },
    allDone: function() {
        let bool = arguments[0]
        console.log(bool);
        let homeWork = document.querySelector('.homeWork')
        bool ? homeWork.classList.add('allDone') : homeWork.classList.remove('allDone')
    }


}
!function(window) {
    //1.检测是否有本地名单,有的话将名单挂载
    let list = localStorage.getItem('list')
    //2.是否有班级名称
    let name = localStorage.getItem('class')
    if (name) document.querySelector('.class').textContent = `${name}班级` || '班级名称'
    if (!list) return hw.list= null
    hw.list = JSON.parse(list)
    
    

}(window)



function toDom (dom,data) {
    let str = dom.innerHTML
    str = ''
    for (let i = 0; i < data.length; i++) {

        str += `<li class="item undone">${data[i]}</li>`
    }
    dom.innerHTML = str
}
//给每一个学员作业添加手动完成效果
!function() {
    let students = document.querySelectorAll('.con .item')
    let header = document.querySelector('.header > h1')
    let pab = document.querySelector('#pab')
    /* 鼓掌音频 */
    pab.addEventListener('timeupdate', function() {
        console.log('111', this.currentTime);
        if (this.currentTime >= 1.5) {
            this.pause()
            this.currentTime = 0
        }
    })
    students.forEach(student => {
        student.onclick = function() {
            if(window.specialMan) {
                //如果特殊任务，所有点击，改为添加人员
                console.log(student);
                window.specialMan.push(student.textContent)
                return
            }
            let classList = student.classList
            classList.toggle('done')
            classList.toggle('undone')
            console.log('111');
            //鼓掌
            if (classList.contains('done')) {
                //头部文字改变
                header.textContent = `${this.textContent}完成作业,棒棒棒🌹🌹🌹`
                header.style.color = '#f00'
                pab.play()
            } else {

                header.textContent = '班级作业检查&单词纠错'
                 header.style.color = '#000'
            }
            //全部完成变色
            let flag = true
            students.forEach(item => {
                if(item.className.indexOf('undone') !== -1) {
                    flag = false
                }
            })
            if(flag){
                 header.textContent = '全部完成作业,无敌!!!!'
                return hw.allDone = true
            } 
            hw.allDone = false
        }
    })
}()

//点击添加班级名单
!function() {
    let addClass = document.querySelector('.addClass')
    let addInput = document.querySelector('#addInput')
    addInput.addEventListener('change', function(e) {
       
        const fileReader = new FileReader()
        let file = this.files[0]
        let className = file.name
        className = className.replace(/[^0-9]+/gi, " ").trim()
        if (className) {
            localStorage.setItem('class', className)
        } else {
            localStorage.setItem('class', '')
        }
        console.log(className, '---className');
        fileReader.readAsText(file)
        
        fileReader.onloadend = function(e) {

            let str = this.result
            console.log(str);
            str = str.replace(/[^\u4e00-\u9fa5]+/ig, ' ')

            let arr = str.split(' ')
            arr = arr.filter(item => {
                return item && Boolean(item)  
            })
            console.log(arr);
            localStorage.setItem('list', JSON.stringify(arr))
            hw.list = arr
        }
       
    })
    addClass.onclick = function() {
        addInput.click()
    }
  
}()


//autoCheck自动检查
!function() {
    let autoCheck = document.querySelector('.autoCheck')
    let header = document.querySelector('.header > h1')
    let checkDir = document.querySelector('.checkDir')
    autoCheck.onclick = function() {
        checkDir.style.display = 'block'
    
    }
    checkDir.addEventListener('keydown', function(e) {
        if(e.code === 'Enter') {
            let dir = checkDir.children[0].value
            //转义
            dir = window.decodeURIComponent(dir)
            check({dir})
        }
    })
    function check(dir) {
        //读取文件夹目录，发送文件夹目录
        fetch(`http://localhost:8085/getHomework?dir=${dir}`)
        .then(function(response) {
            return response.json()
            
        })
        .then(function(data) {
            let { arr } = data
            console.log(arr);
            if(!arr || arr.length ===0 ) return alert('今天没有完成的作业')
            let items = document.querySelectorAll('.con .item')
            arr.forEach(item => {
               
            items.forEach(dom => {
                   if(item.indexOf(dom.textContent) !== -1)  {
                    doneS = true
                    header.textContent = `${item}完成作业,棒棒棒🌹🌹🌹`
                    header.style.color = '#f00'
                    dom.classList.add('done')
                    pab.play()
                   }
                })
              
            })
        })
    }
}()

//点名系统
function handleChooseOne() {
    let flag = false // 是否开始点名
    let timer = null // 定时器
    let list = hw.list // 班级名单
    let last = null // 上一次选中的人
    return function(){
        let btn = document.querySelector('.chooseOne')
        let doms = document.querySelectorAll('.con .item')
        console.log(flag);
        if(!flag) {
            btn.textContent = '停止'
            btn.style.backgroundColor = 'red'
            function choose() {
                if(last !== null) {
                    doms[last].classList.remove('done')
                }
                let random = getRandom(0, list.length - 1)     
                console.log(doms, last);
                last = random
                console.log(random);
                doms[last].classList.add('done')
                flag = true
            }
            choose()
            timer = setInterval(() => {
            
                choose()
            }, 200);
        } else {
            btn.textContent = '点名'
            btn.style.backgroundColor = 'orange'
            flag = false
            clearInterval(timer)
            timer = null
            if(window.specialMan && window.specialMan.length !== 0 ) {
                //如果又精准部署，且列队不为空
                if(last !== null) {
                    console.log(333);
                    doms[last].classList.remove('done')
                }
                let man = window.specialMan.pop()
                console.log(man);
                let index = list.findIndex((item) => {
                    return item === man
                })
                doms[index].classList.add('done')
                last = index
            }
        }
    }
}

// 注册点击事件
!function () { 
    document.querySelector('.chooseOne').addEventListener('click',handleChooseOne())
 }()
//随机正整数函数
function getRandom(min,max) {
    return Math.floor(Math.random()*(max-min +1) + min)
}
// console.log(getRandom(1,3));


//鼠标右击出现tooltip弹出框
document.addEventListener('mousedown', function(e) {
    let div
    if(e.button === 1) {
        // 右击 在中键的位置生成确认精准点名
        let btn = document.querySelector('.precision-call')
        //如果已经存在 不制造,只控制显示隐藏
        if(btn) {
            console.log(e.clientX,e.clientY);
            btn.style.left = e.clientX + 'px'
            btn.style.top = e.clientY + 'px'
            if(btn.classList.contains('show')) {
                btn.classList.remove('show')
                btn.style.display = 'none'
            } else {
                btn.classList.add('show')
                btn.style.display = 'block'
            }
            return
        }
        
        div = document.createElement('div')
        div.className = 'precision-call show' 
        document.body.appendChild(div)
        // 位置，根据鼠标位置来 ，水平与鼠标位置一致， 垂直移动自身一个距离
        div.style.left = e.clientX + 'px'
        div.style.top = e.clientY + 'px'
        div.style.backgroundColor = 'rgb(36, 141, 32)'
        div.style.color = '#fff';
        div.style.padding = '5px 10px'
        div.style.zIndex = '9999'
        div.textContent  = '部署精确点名'
        div.style.cursor = 'pointer'
        div.style.borderRadius = '5px'

        // 注册时间，点击表示确定
        div.addEventListener('click', function() {
            //点击，添加全局变量一个用来记录，名单
            window.specialMan = []
            //关闭
            div.style.display = 'none'
            div.classList.remove('show')
        })
    
    }
})